package com.xbongbong.saas.service.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.dto.FormDataAddGetDTO;
import com.xbongbong.paas.pojo.vo.FormDataAddGetVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.GaodeGeoHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.OkHttpUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.pro.common.pojo.AddressPojo;
import com.xbongbong.pro.constant.BaseConfig;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.customer.pojo.dto.Base64DecodeMultipatrFile;
import com.xbongbong.pro.customer.pojo.dto.ScanCardDTO;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.ContactErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.CustomerErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.LinkFormItemDTO;
import com.xbongbong.pro.formexplain.pojo.vo.LinkFormItemVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.PhoneExtEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.service.ScanCardService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author jiping.yang
 * @Title: 名片扫描实现类
 * @date 2021/5/20 15:34
 */
@Service("scanCardService")
public class ScanCardServiceImpl implements ScanCardService {

    private static final Logger LOG = LoggerFactory.getLogger(ScanCardServiceImpl.class);

    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private PaasFormExplainService paasFormExplainService;

    public BaseVO customerCardSet(JSONObject resultObj,ScanCardDTO scanCardDTO) throws XbbException {
        String prefix = RedisPrefixConstant.BUZ_CARD_DATA;
        String key = scanCardDTO.getCorpid() + ":" + scanCardDTO.getUserId();
        // 处理扫描结果
        JSONArray jsonObject = resultObj.getJSONArray("item_list");
        JSONObject vaildData = new JSONObject();
        Integer isCompany = scanCardDTO.getIsCompany();
        dealScanCardData(jsonObject, vaildData);
        vaildData.put("formId",scanCardDTO.getFormId());
        vaildData.put("isCompany",isCompany);
        paasRedisHelper.setValue(prefix, key, vaildData, RedisTimeConstant.SHORT_DURATION);
        return new BaseVO();
    }

    private void contactCardSet(JSONObject resultObj, ScanCardDTO scanCardDTO) throws XbbException {
        String prefix = RedisPrefixConstant.BUZ_CONTACT_CARD_DATA;
        String key = scanCardDTO.getCorpid() + ":" + scanCardDTO.getUserId();
        // 处理扫描结果
        JSONArray jsonObject = resultObj.getJSONArray("item_list");
        JSONObject vaildData = new JSONObject();
        dealScanCardData(jsonObject, vaildData);
        vaildData.put("formId", scanCardDTO.getFormId());
        paasRedisHelper.setValue(prefix, key, vaildData, RedisTimeConstant.SHORT_DURATION);
    }

    private void dealScanCardData(JSONArray ccData, JSONObject vaildData) {
        for (Object ccDatum : ccData) {
            JSONObject data = (JSONObject) ccDatum;
            //vaildData.put(data.getString("description"),data.getString("value"));
            String key = data.getString("description");
            String value = data.getString("value");
            if (!vaildData.containsKey(key)){
                vaildData.put(key,value);
            }
        }
    }
    /**
     * 新建客户
     *
     * @param baseDTO
     * @return
     * @throws XbbException
     */
    @Override
    public FormDataAddGetVO customerCardGet(BaseDTO baseDTO) throws XbbException {
        LOG.info("调用 ScanCardServiceImpl.customerCardGet");
        String prefix = RedisPrefixConstant.BUZ_CARD_DATA;
        String key = baseDTO.getCorpid() + ":" + baseDTO.getUserId();
        JSONObject customerCard = JSONObject.parseObject(paasRedisHelper.getValue(prefix, key));
        FormDataAddGetDTO formDataAddGetDTO = new FormDataAddGetDTO();
        formDataAddGetDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        formDataAddGetDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        List<PaasFormEntityExt> paasFormEntityExtList = paasFormService.getEnableCustomerFormList(baseDTO.getLoginUser());
        if (paasFormEntityExtList.isEmpty()) {
            throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201034);
        }
        //PaasFormEntity paasFormEntity = paasFormEntityExtList.get(0);
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        for (PaasFormEntity paasFormEnt : paasFormEntityExtList){
            if (Objects.equals(paasFormEnt.getId(),customerCard.getLong("formId"))){
                paasFormEntity = paasFormEnt;
            }
        }
        BeanUtil.copyProperties(paasFormEntity, formDataAddGetDTO);
        //formDataAddGetDTO.setFormId(paasFormEntity.getId());
        formDataAddGetDTO.setFormId(customerCard.getLong("formId"));
        formDataAddGetDTO.setLoginUser(baseDTO.getLoginUser());
        FormDataAddGetVO formDataAddGetVO = paasFormDataService.addGet(formDataAddGetDTO);

        boolean isCompany = Objects.equals(customerCard.getInteger("isCompany"),BasicConstant.ONE);
        List<FieldAttrEntity> explainList = formDataAddGetVO.getExplainList();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            DefaultAttrPoJo defaultAttrPoJo = fieldAttrEntity.getDefaultAttr();
            if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.WEBSITE.getAttr()) && Objects.nonNull(customerCard.get("网址"))) {
                defaultAttrPoJo.setDefaultValue(customerCard.get("网址"));
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
            }
            if (isCompany){
                if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.NAME.getAttr()) && Objects.nonNull(customerCard.get("公司"))) {
                    defaultAttrPoJo.setDefaultValue(customerCard.get("公司"));
                    fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
                }
            }else{
                if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.NAME.getAttr()) && Objects.nonNull(customerCard.get("姓名"))) {
                    defaultAttrPoJo.setDefaultValue( customerCard.get("姓名"));
                    fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
                }
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.PHONE.getAttr())) {
                List<JSONObject> phoneList = new ArrayList<>();
                // dealPhoneExt(customerCard, phoneList, "work_tel", "work_tel", PhoneExtEnum.WORK);
                // 暂时不放开
                String workTel = "手机";
                if (customerCard.containsKey("手机") && (Objects.isNull(customerCard.getString("手机")) || StringUtils.isEmpty(customerCard.getString("手机")))){
                    workTel = "电话";
                }
                dealPhoneExt(customerCard, phoneList, workTel, PhoneExtEnum.TEL);
                // dealPhoneExt(customerCard, phoneList, "fax", "fax", PhoneExtEnum.FAX);
                defaultAttrPoJo.setDefaultValue(phoneList);
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.ADDRESS.getAttr()) && Objects.nonNull(customerCard.getString("地址"))) {
                String address = customerCard.getString("地址");
                JSONObject geoObj = new JSONObject();
                try {
                    geoObj = GaodeGeoHelper.geo(address, "");
                } catch (Exception e) {
                    LOG.warn("地址转经纬度失败", e.getMessage());
                }
                AddressPojo addressPojo = new AddressPojo();
                addressPojo.setAddress(address);
                if (geoObj != null && !geoObj.isEmpty()) {
                    addressPojo.setProvince(geoObj.getString("province"));
                    addressPojo.setCity(geoObj.getString("city"));
                    addressPojo.setDistrict(geoObj.getString("district"));
                    addressPojo.setLatAndLon(geoObj.getDouble("latitude"), geoObj.getDouble("longitude"));
                } else {
                    addressPojo.setProvince("");
                    addressPojo.setCity("");
                    addressPojo.setDistrict("");
                    addressPojo.setAddress("");
                }
                defaultAttrPoJo.setDefaultValue(addressPojo);
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
            }
            //将所有的信息都放入备注中，返回给前端
            if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.MEMO.getAttr()) && Objects.nonNull(customerCard)){
                StringBuilder obj= new StringBuilder();
                for (Map.Entry<String, Object> entry : customerCard.entrySet()) {
                    if (!Objects.equals(entry.getKey(),"isCompany") && !Objects.equals(entry.getKey(),"formId")){
                        if (Objects.nonNull(entry.getValue()) && StringUtils.isNotEmpty(String.valueOf(entry.getValue()))){
                            obj.append(entry.getKey()).append(":").append(entry.getValue()).append("\n");
                        }
                    }
                }
                defaultAttrPoJo.setDefaultValue(obj.toString());
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
            }
        }
        return formDataAddGetVO;
    }

    @Override
    public FormDataAddGetVO contactCardGet(BaseDTO baseDTO) throws XbbException {
        LOG.info("调用 ScanCardServiceImpl.contactCardGet");
        String prefix = RedisPrefixConstant.BUZ_CONTACT_CARD_DATA;
        String key = baseDTO.getCorpid() + ":" + baseDTO.getUserId();
        JSONObject contactCard = JSONObject.parseObject(paasRedisHelper.getValue(prefix, key));
        if (Objects.isNull(contactCard)) {
            throw new XbbException(ContactErrorCodeEnum.API_ERROR_204012);
        }
        FormDataAddGetDTO formDataAddGetDTO = new FormDataAddGetDTO();
        formDataAddGetDTO.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());
        formDataAddGetDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        List<PaasFormEntityExt> paasFormEntityExtList = paasFormService.getEnableContactFormList(baseDTO.getLoginUser());
        if (paasFormEntityExtList.isEmpty()) {
            throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201036);
        }
        Long formId = contactCard.getLong(StringConstant.FORM_ID);
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        for (PaasFormEntity paasFormEnt : paasFormEntityExtList) {
            if (Objects.equals(paasFormEnt.getId(), formId)) {
                paasFormEntity = paasFormEnt;
            }
        }
        BeanUtil.copyProperties(paasFormEntity, formDataAddGetDTO);
        formDataAddGetDTO.setFormId(formId);
        formDataAddGetDTO.setLoginUser(baseDTO.getLoginUser());
        FormDataAddGetVO formDataAddGetVO = paasFormDataService.addGet(formDataAddGetDTO);

        List<FieldAttrEntity> explainList = formDataAddGetVO.getExplainList();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            DefaultAttrPoJo defaultAttrPoJo = fieldAttrEntity.getDefaultAttr();
            if (Objects.equals(fieldAttrEntity.getAttr(), ContactEnum.NAME.getAttr())) {
                Object name = contactCard.get("姓名");
                if (Objects.nonNull(name)) {
                    defaultAttrPoJo.setDefaultValue(name);
                    fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
                }
            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContactEnum.PHONE.getAttr())) {
                List<JSONObject> phoneList = new ArrayList<>();
                // dealPhoneExt(customerCard, phoneList, "work_tel", "work_tel", PhoneExtEnum.WORK);
                // 暂时不放开
                String workTel = "手机";
                if (contactCard.containsKey(workTel) && (Objects.isNull(contactCard.getString(workTel)) || StringUtils.isEmpty(contactCard.getString(workTel)))) {
                    workTel = "电话";
                }
                dealPhoneExt(contactCard, phoneList, workTel, PhoneExtEnum.TEL);
                defaultAttrPoJo.setDefaultValue(phoneList);
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContactEnum.ADDRESS.getAttr())) {
                String address = contactCard.getString("地址");
                if (Objects.nonNull(address)) {
                    JSONObject geoObj = new JSONObject();
                    try {
                        geoObj = GaodeGeoHelper.geo(address, "");
                    } catch (Exception e) {
                        LOG.warn("ScanCardServiceImpl.contactCardGet 地址转经纬度失败", e.getMessage());
                    }
                    AddressPojo addressPojo = new AddressPojo();
                    addressPojo.setAddress(address);
                    if (MapUtil.isNotEmpty(geoObj)) {
                        addressPojo.setProvince(geoObj.getString(BusinessConstant.PROVINCE));
                        addressPojo.setCity(geoObj.getString(BusinessConstant.CITY));
                        addressPojo.setDistrict(geoObj.getString(BusinessConstant.DISTRICT));
                        addressPojo.setLatAndLon(geoObj.getDouble(BusinessConstant.LATITUDE), geoObj.getDouble(BusinessConstant.LONGITUDE));
                    } else {
                        addressPojo.setProvince("");
                        addressPojo.setCity("");
                        addressPojo.setDistrict("");
                        addressPojo.setAddress("");
                    }
                    defaultAttrPoJo.setDefaultValue(addressPojo);
                    fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
                }
            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContactEnum.MEMO.getAttr())) {
                //将所有的信息都放入备注中，返回给前端
                StringBuilder obj = new StringBuilder();
                for (Map.Entry<String, Object> entry : contactCard.entrySet()) {
                    if (!Objects.equals(entry.getKey(), StringConstant.FORM_ID)) {
                        if (Objects.nonNull(entry.getValue()) && StringUtils.isNotEmpty(String.valueOf(entry.getValue()))) {
                            obj.append(entry.getKey()).append(StringConstant.COLON).append(entry.getValue()).append("\n");
                        }
                    }
                }
                defaultAttrPoJo.setDefaultValue(obj.toString());
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
            }
        }
        return formDataAddGetVO;
    }

    /**
     *  处理联系方式字段
     * @param customerCard
     * @param phoneList
     * @param work_tel 电话类型key
     * @param work
     */
    private void dealPhoneExt(JSONObject customerCard, List<JSONObject> phoneList, String work_tel, PhoneExtEnum work) {
        String work_telephone = customerCard.getString(work_tel);
        if (StringUtil.isNotEmpty(work_telephone)) {
            JSONObject phone = new JSONObject();
            JSONObject text1Obj = new JSONObject();
            text1Obj.put("text", work.getName());
            text1Obj.put("value", work.getCode());
            phone.put("text_1", text1Obj);
            phone.put("text_2", work_telephone);
            phoneList.add(phone);
        }
    }

    /**
     * 客户关联新建联系人
     *
     * @param baseDTO
     * @return
     * @throws XbbException
     */
    @Override
    public LinkFormItemVO customerCardContactGet(BaseDTO baseDTO) throws XbbException {
        LOG.info("调用 ScanCardServiceImpl.customerCardContactGet");

        LinkFormItemDTO linkFormItemDTO = new LinkFormItemDTO();
        BeanUtil.copyProperties(baseDTO, linkFormItemDTO);
        linkFormItemDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        String prefix = RedisPrefixConstant.BUZ_CARD_DATA;
        String key = baseDTO.getCorpid() + ":" + baseDTO.getUserId();
        JSONObject customerCardDTO = JSONObject.parseObject(paasRedisHelper.getValue(prefix, key));
        linkFormItemDTO.setLinkBusinessType(XbbRefTypeEnum.CONTACT.getCode());
        linkFormItemDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        LinkFormItemVO linkFormItemVO = paasFormExplainService.linkFormList(linkFormItemDTO);
        if (Objects.equals(customerCardDTO.getInteger("isCompany"), 1)) {
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            JSONObject data = new JSONObject();
            String name = customerCardDTO.getString("name");
            if (Objects.nonNull(name)) {
                data.put(ContactEnum.NAME.getAttr(), name);
            }
            String telephone = customerCardDTO.getString("telephone");
            if (!Objects.isNull(telephone) ) {
                List<JSONObject> phoneList = new ArrayList<>();
                dealPhoneExt(customerCardDTO, phoneList, "work_tel", PhoneExtEnum.WORK);
                // 暂时不放开
                // dealPhoneExt(customerCardDTO, phoneList, "telephone", "telephone", PhoneExtEnum.TEL);
                // dealPhoneExt(customerCardDTO, phoneList, "fax", "fax", PhoneExtEnum.TEL);
                data.put(ContactEnum.PHONE.getAttr(),phoneList);
            }
            String title = customerCardDTO.getString("title");
            if (Objects.nonNull(title)) {
                data.put(ContactEnum.POSITION.getAttr(), title);
            }
            paasFormDataEntityExt.setData(data);
            linkFormItemVO.setFormDataList(Collections.singletonList(paasFormDataEntityExt));
        }

        return linkFormItemVO;
    }

    /**
     * 名片扫描调用接口获取数据
     * @param
     * @return
     * @throws XbbException
     */
    @Override
    public BaseVO requestCcCard(ScanCardDTO scanCardDTO) throws XbbException {
        Integer businessType = scanCardDTO.getBusinessType();
        LOG.info("名片扫描调用接口获取数据:businessType={},picfile={}", scanCardDTO.getBusinessType(), scanCardDTO.getPicFile());
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        // 后面业务类型多起来转策略，名片扫描这应该只有客户和联系人啦
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                return requestCcCard4Customer(scanCardDTO);
            case CONTACT:
                return requestCcCard4Contact(scanCardDTO);
            default:
        }
        return null;
    }

    /**
     * 客户名片扫描，这是老逻辑，所以请求三方接口的方式没有改动
     * 新的请求三方接口的方式见：
     * @see ScanCardServiceImpl#getRequestCcCardResult(ScanCardDTO)
     * @param scanCardDTO
     * @return
     * @throws XbbException
     */
    private BaseVO requestCcCard4Customer(ScanCardDTO scanCardDTO) throws XbbException {
        String url = BaseConfig.getUrl();
        String appKey = BaseConfig.getKey();
        String appSecret = BaseConfig.getSecret();
        BufferedReader in = null;
        DataOutputStream out = null;
        HttpURLConnection conn = null;
        String result = "";
        try {
            byte[] bytes = Base64DecodeMultipatrFile.getFileStream(scanCardDTO.getPicFile());
            URL realUrl = new URL(url);
            conn = (HttpURLConnection)realUrl.openConnection();
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("app-key",appKey);
            conn.setRequestProperty("app-secret",appSecret);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            out = new DataOutputStream(conn.getOutputStream());
            out.write(bytes);
            out.flush();
            out.close();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            LOG.info("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        JSONObject resultObj = JsonHelperUtil.parseObject(result);
        Integer code = FastJsonHelper.getIntegerOrDefaultFromFormData(resultObj , StringConstant.CODE , 0);
        if (!BasicConstant.CC_CARD.equals(code)) {
            LOG.info("ScanCardServiceImpl.requestCcCard4Customer ccCard:{}", resultObj.getString("message"));
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        JSONObject jsonObject = JsonHelperUtil.parseObject(resultObj.getString("result"));
        customerCardSet(jsonObject,scanCardDTO);
        return  null;
    }

    /**
     * 联系人名片扫描
     * @param scanCardDTO
     * @return
     * @throws XbbException
     */
    private BaseVO requestCcCard4Contact(ScanCardDTO scanCardDTO) throws XbbException{
        JSONObject jsonObject = getRequestCcCardResult(scanCardDTO);
        if (Objects.nonNull(jsonObject)) {
            contactCardSet(jsonObject,scanCardDTO);
        }
        return new BaseVO();
    }

    /**
     * 得到扫描名片的结果,请求三方接口使用的是okHttp
     * @param scanCardDTO
     * @return 返回值可能为null,使用时记得判空
     */
    private JSONObject getRequestCcCardResult(ScanCardDTO scanCardDTO){
        String url = BaseConfig.getUrl();
        String appKey = BaseConfig.getKey();
        String appSecret = BaseConfig.getSecret();
        Map<String, String> headers = new HashMap<>(BasicConstant.THREE);
        headers.put("connection", "Keep-Alive");
        headers.put("Content-Type", "application/octet-stream");
        headers.put("Charset", "UTF-8");
        headers.put("app-key", appKey);
        headers.put("app-secret", appSecret);
        try {
            // 和 Base64DecodeMultipatrFile.getFileStream  返回的数据可能不一样，按照系统给的picFile则是一样的
            String result = OkHttpUtil.post(url, OkHttpUtil.getBytes4DecodeUrl(scanCardDTO.getPicFile()), "application/octet-stream", headers);
            if (StringUtil.isNotEmpty(result)) {
                JSONObject resultObj = JsonHelperUtil.parseObject(result);
                Integer code = FastJsonHelper.getIntegerOrDefaultFromFormData(resultObj , StringConstant.CODE , 0);
                if (!BasicConstant.CC_CARD.equals(code)) {
                    LOG.info("ScanCardServiceImpl.getRequestCcCardResult ccCard:{}", resultObj.getString("message"));
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                JSONObject jsonObject = JsonHelperUtil.parseObject(resultObj.getString("result"));
                return jsonObject;
            }
        } catch (Exception e) {
            LOG.error("ScanCardServiceImpl.getRequestCcCardResult 发送 POST 请求出现异常！", e);
        }
        return null;
    }
}
